import { h, ref, onMounted, onUnmounted } from 'vue'
import { fetchInlineScriptsSet } from '@/utils/versionCheck'
export default function withVersionCheck(WrappedComponent) {
    return {
        name: `WithVersionCheck(${WrappedComponent.name || 'Component'})`,
        setup(props, { attrs, slots, emit }) {
            const lastScriptsSet = ref(null)
            const showUpdatePrompt = ref(false)
            const checkIntervalMs = 3000
            let checkTimer = null

            function areSetsEqual(setA, setB) {
                if (setA.size !== setB.size) return false
                for (const item of setA) {
                    if (setB.has(item)) return false
                }
                return true
            }

            async function checkVersion() {
                const currentSet = await fetchInlineScriptsSet()
                console.log(currentSet)
                if (!currentSet) return
                if (lastScriptsSet.value) {
                    if (!areSetsEqual(lastScriptsSet.value, currentSet)) {
                        showUpdatePrompt.value = true
                        clearInterval(checkTimer)
                    }
                } else {
                    lastScriptsSet.value = currentSet
                }
            }

            function reloadPage() {
                window.location.reload(true)
            }

            onMounted(() => {
                checkVersion()
                checkTimer = setInterval(checkVersion, checkIntervalMs)
            })

            onUnmounted(() => {
                clearInterval(checkTimer)
            })

            return () => [
                h(WrappedComponent, { ...attrs, ...props, on: emit }, slots),
                showUpdatePrompt.value &&
                h('div', {
                    style: {
                    position: 'fixed',
                    bottom: '10px',
                    right: '10px',
                    background: '#fffae6',
                    border: '1px solid #f0c36d',
                    padding: '12px 20px',
                    borderRadius: '4px',
                    boxShadow: '0 0 6px rgba(0,0,0,0.15)',
                    zIndex: 9999
                    }
                }, [
                    '检测到新版本，',
                    h('button', {
                    onClick: reloadPage,
                    style: { marginLeft: '10px', cursor: 'pointer' }
                    }, '点击刷新')
                ])
            ]
        }
    }
}